import os
import shutil
from datetime import datetime
import logging
from typing import Optional
from src.config.settings import settings

logger = logging.getLogger(__name__)

class BackupService:
    """备份服务类"""
    
    def __init__(self):
        self.backup_dir = settings.BACKUP_DIR or "./backups"
        os.makedirs(self.backup_dir, exist_ok=True)
    
    def backup_database(self, db_path: str, backup_name: Optional[str] = None) -> str:
        """
        备份数据库文件
        
        Args:
            db_path: 数据库文件路径
            backup_name: 备份名称（可选）
            
        Returns:
            备份文件路径
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        if not backup_name:
            backup_name = f"db_backup_{timestamp}"
        
        backup_path = os.path.join(self.backup_dir, f"{backup_name}.db")
        
        try:
            shutil.copy2(db_path, backup_path)
            logger.info(f"数据库备份成功: {backup_path}")
            return backup_path
        except Exception as e:
            logger.error(f"数据库备份失败: {e}")
            raise
    
    def backup_knowledge_graph(self, neo4j_dir: str, backup_name: Optional[str] = None) -> str:
        """
        备份知识图谱数据
        
        Args:
            neo4j_dir: Neo4j数据目录
            backup_name: 备份名称（可选）
            
        Returns:
            备份目录路径
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        if not backup_name:
            backup_name = f"kg_backup_{timestamp}"
        
        backup_path = os.path.join(self.backup_dir, backup_name)
        
        try:
            shutil.copytree(neo4j_dir, backup_path)
            logger.info(f"知识图谱备份成功: {backup_path}")
            return backup_path
        except Exception as e:
            logger.error(f"知识图谱备份失败: {e}")
            raise
    
    def cleanup_old_backups(self, days_to_keep: int = 7):
        """
        清理过期备份
        
        Args:
            days_to_keep: 保留天数
        """
        try:
            current_time = datetime.now()
            for filename in os.listdir(self.backup_dir):
                file_path = os.path.join(self.backup_dir, filename)
                file_time = datetime.fromtimestamp(os.path.getctime(file_path))
                
                if (current_time - file_time).days > days_to_keep:
                    if os.path.isfile(file_path):
                        os.remove(file_path)
                    elif os.path.isdir(file_path):
                        shutil.rmtree(file_path)
                    
                    logger.info(f"已删除过期备份: {file_path}")
        except Exception as e:
            logger.error(f"清理过期备份失败: {e}")

# 全局实例
_backup_service: Optional[BackupService] = None

def get_backup_service() -> BackupService:
    """获取备份服务单例实例"""
    global _backup_service
    if _backup_service is None:
        _backup_service = BackupService()
    return _backup_service